package cn.itsource.system.service.impl;

import cn.itsource.base.util.AjaxResult;
import cn.itsource.base.util.BusinessKey;
import cn.itsource.system.domain.dto.PhoneUserFormRegisterDto;
import cn.itsource.system.mapper.UserMapper;
import cn.itsource.system.service.ILogininfoService;
import cn.itsource.system.service.IRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class RegisterServiceImpl implements IRegisterService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private ILogininfoService logininfoService;
    @Autowired
    private UserMapper userMapper;
    @Override
    public AjaxResult userRegister(PhoneUserFormRegisterDto registerDto) {
        //逻辑
        String phone = registerDto.getPhone();
        String key = BusinessKey.BK_REGISTER+BusinessKey.BK_SPLIT+phone;
        //判断用户输入的验证码和redis里面的存放的验证码  是不是一样的
        if (!redisTemplate.hasKey(key)) {
            return AjaxResult.me().setMessage("验证码已过期").setSuccess(false);
        }
        Object o = redisTemplate.opsForValue().get(key);//得到用户之前存放的code
        if(!o.toString().equalsIgnoreCase(registerDto.getPhoneCode())){
            return AjaxResult.me().setMessage("手机验证码不匹配").setSuccess(false);
        }
        //验证手机号是否已经被注册过
        Long count = userMapper.selectByPhone(phone);
        if(count != 0){
            return AjaxResult.me().setMessage("手机号已被注册").setSuccess(false);
        }
        //密码是否一致
        if(!registerDto.getPassword().equals(registerDto.getPasswordRepeat())){
            return AjaxResult.me().setMessage("两次密码不一致").setSuccess(false);
        }
        //保存数据库--- logininfo  user表
        logininfoService.register(registerDto,1);//1表示是 用户
        return AjaxResult.me();
    }
}
